import mutationTypes from "./mutation-types";
import { Toast } from 'vant';

const actions = {
  
  // 加载播放状态
  loadVideoStatus({ commit }) {
    // 发送异步请求 axios.get(...)
    if (window.localStorage.isPlayed) {
      let videoStatus = JSON.parse(window.localStorage.isPlayed);
      commit(mutationTypes.SET_PLAY_STATUS, videoStatus);
    }
  },

  // 加载购物车数据
  loadCartStatus({ commit }) {
    if (window.localStorage.cart) {
      let cart = JSON.parse(window.localStorage.cart)
      commit(mutationTypes.SET_CART_STATUS, cart)
    }
  },

  // 添加商品到购物车
  addProdToCart({ commit, state }, prod) {
    const cartItem = state.cart.find(item => item.id === prod.id);
    if (cartItem) {
      commit(mutationTypes.INCREMENT_PROD_QUANTITY, cartItem)
      Toast('购物车中已存在该商品')
    } else {
      commit(mutationTypes.ADD_PROD_TO_CART, prod)
      Toast('商品添加成功')
    }
  },

  // 从购物车移除商品
  removeProd({ commit, state }, id) {
    const cart = state.cart
    cart.splice(cart.findIndex(item => item.id === id), 1)
    commit(mutationTypes.SET_CART_STATUS, cart)
    window.localStorage.cart = JSON.stringify(cart)
  }
}

export default actions